<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <button onclick="send()">发送 同步 请求</button>
    <button onclick="sendAsync()">发送 ajax 请求</button>
    <button onclick="doConsole()">打印</button>
    <script>
      /**
       *  请求：
       *     简单请求
       *
       */

      function send() {
        let http = new XMLHttpRequest();

        // 同步请求
        http.open(
          "get",
          "http://localhost/test?username=admin&password=123456",
          false
        );

        http.onreadystatechange = () => {
          console.log(http.readyState, http.status);
          if (http.readyState == 4 && http.status == 200) {
            console.log("请求成功!");
            console.log(http.responseText);
            console.log(JSON.parse(http.responseText));
          }
        };

        // 发送请求
        http.send();

        console.log("end");
      }

      // 提升
      function sendAsync() {
        let http = new XMLHttpRequest();

        http.open("post", "http://localhost/test", true);

        http.onreadystatechange = () => {
          console.log(http.readyState, http.status);
          if (http.readyState == 4 && http.status == 200) {
            console.log("请求成功!");
            console.log(http.responseText);
            let obj = JSON.parse(http.responseText);
            console.log(obj);
            console.log(typeof obj.timer);
          }
        };

        // a.parse("111"); // error

        // 发送请求
        http.send(
          JSON.stringify({
            username: "lisi",
            password: "22222",
          })
        );

        console.log("end");
      }

      function doConsole() {
        console.log(1111);
      }
    </script>
  </body>
</html>
